# -*- coding: utf-8 -*-
import sys
import arcpy
import pandas as pd
import argparse

def table_to_csv(input_fc="RasterUnitsV4_2003", sel_fields="", saved_csv_filename ="",
                 additional_process_fun=None, csv_encoding="gb2312"):
    '''
        将要素类的属性表转为csv文件
    :param input_fc: Feature Class
        输入的要素类

    :param sel_fields: str
        需要导出的字段列表，字符串形式，以分号;分隔，形式如：Factor_Aspect;Factor_地震点_IDW3

    :param additional_process_fun: function
        函数引用，将sel_fields使用传入的函数进行处理，默认值为None

    :return: str
        返回保存的csv文件名

    '''
    if input_fc is None:
        return None

    # 若未选择需要导出的字段，则导出所有字段（shape字段除外）
    if sel_fields == "":
        # 删除Shape字段
        field_obj_list = arcpy.ListFields(input_fc)
        field_list = [f.name for f in field_obj_list]
        field_list.remove("Shape")
    elif len(sel_fields)!=0:
        field_list = sel_fields.split(";")
        if "OBJECTID" not in field_list:
            field_list.insert(0,"OBJECTID")

    if "Shape_Length" in field_list:
        field_list.remove("Shape_Length")
    if "Shape_Area" in field_list:
        field_list.remove("Shape_Area")
    if "Shape" in field_list:
        field_list.remove("Shape")
    # 使用传入的函数进行额外处理
    if additional_process_fun is not None:
        field_list = additional_process_fun(field_list)

    header_titles = ",".join(field_list)

    try:
        arr = arcpy.da.FeatureClassToNumPyArray(input_fc, field_list, skip_nulls=True)
        # 若没有指定保存文件的路径，则自动设置一个路径
        if saved_csv_filename == "":
            saved_csv_filename = "{0}.csv".format(input_fc)
        df = pd.DataFrame(data=arr, columns=field_list)

        # encoding参数numpy 1.14.0才开始支持（低版本ArcMap没有这么高版本的Numpy），因此换成pandas更好些
        df.to_csv(saved_csv_filename, header=header_titles, encoding=csv_encoding, index=False)

        success_str = "write file '{0}' to csv successful!".format(saved_csv_filename)
        arcpy.AddMessage(success_str)
        return saved_csv_filename

    except Exception:
        arcpy.AddMessage("error:")
        e = sys.exc_info()
        arcpy.AddMessage(str(e.args))

def main():
    parser = argparse.ArgumentParser(description='要素类属性表导出为CSV脚本')
    parser.add_argument('--gdb', required=True, help='工作空间')
    parser.add_argument('--input_fc', required=True, help='输入的要素类')
    parser.add_argument('--export_fields', required=True, help='被导出的多个字段，字符串形式，以分号;分隔，')
    parser.add_argument('--csv_file_path', required=True, help='输出CSV文件的完整路径')
    parser.add_argument('--csv_encoding', required=True, help='输出CSV文件的编码')

    args = parser.parse_args()
    arcpy.env.workspace = args.gdb
    table_to_csv(input_fc=args.input_fc, sel_fields=args.export_fields, saved_csv_filename=args.csv_file_path, csv_encoding=args.csv_encoding)

if __name__ == "__main__":
    main()
    # input_fc = arcpy.GetParameterAsText(0)
    # export_fields = arcpy.GetParameterAsText(1)
    # csv_file_path = arcpy.GetParameterAsText(2)
    # csv_encoding = arcpy.GetParameterAsText(3)
    # export_fields = export_fields.strip()
    # csv_file_path = csv_file_path.strip()
    #
    # table_to_csv(input_fc=input_fc, sel_fields=export_fields, saved_csv_filename=csv_file_path, csv_encoding=csv_encoding)

    # # 代码模式下，需要设定工作区间
    # arcpy.env.workspace = "G:/DataForDoctorPaper/博士论文数据.gdb"
    # export_fields = "Factor_Aspect;Factor_地震点_IDW3;Factor_断层距离;Factor_流路长度"
    # table_to_csv(input_fc='RasterUnitsV4_2003', year=2003, sel_fields=export_fields, saved_filename=csv_file_path)